/**
 * 
 */
package com.omega.dao.impl;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import org.springframework.stereotype.Repository;
import com.omega.dao.GenericDao;

/**
 * @author vpan14
 * 
 */
@Repository
public class GenericDaoImpl<T extends Serializable> implements GenericDao<T> {

	private Class<T> clazz;

	@PersistenceContext(type = PersistenceContextType.EXTENDED)
	private EntityManager entityManager;

	@Override
	public void save(T object) {
		entityManager.persist(object);
	}

	@Override
	public void delete(T object) {
		entityManager.remove(object);
	}

	@Override
	public void update(T object) {
		entityManager.merge(object);
	}

	@Override
	public T loadByid(long id) {
		return entityManager.find(clazz, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<T> loadAll() {
		return entityManager.createQuery("from " + clazz.getName()).getResultList();
	}

	@Override
	public void deleteById(final long id) {
		final T entity = loadByid(id);
		delete(entity);
	}
	
	public final void setClazz(final Class<T> clazzToSet) {
	        this.clazz = clazzToSet;
	    }

}
